/*
 * @Descripttion: 
 * @version: 
 * @Author: kk
 * @Date: 2020-12-07 18:50:45
 * @LastEditors: kk
 * @LastEditTime: 2020-12-08 21:55:14
 */
import router, { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return false;
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export const loadView = (view) => { // 路由懒加载
  return () => Promise.resolve(require(`@/views/${view}`).default)
}


export function filterAsyncRoutesPerm(menuList) {
  const res = []
  menuList.forEach(route => {
    const {
      title,
      icon,
      breadcrumb,
      activeMenu,
      noCache,
      affix
    } = route.meta || {}
    const isLink = route.path.startsWith('http')
    var myComponent = resolve => {
      require(['@/views/' + route.component + '/index.vue'], resolve)
    }

    const currentRouter = {
      path: route.path || '',
      name: route.name || route.path || Math.random(),
      // 外链不需要component
      // eslint-disable-next-line no-undef
      component:  route.component ? (isLink ? null : loadView(route.component)) : Layout,
      
      meta: {
        title: title,
        icon: icon || undefined,
        breadcrumb: breadcrumb,
        activeMenu: activeMenu,
        affix: affix === true,
        noCache: noCache !== false
      }
    }
    // currentRouter.hidden = route.hidden
    // // 处理有可能出现拼接出两个 反斜杠
    // if (!isLink) {
    //   currentRouter.path = currentRouter.path.replace('//', '/')
    // }
    res.push(currentRouter)
    // 是否有子菜单，并递归处理
    if (route.children && route.children.length > 0) {
      currentRouter.children = filterAsyncRoutesPerm(route.children)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
    
      commit('SET_ROUTES', accessedRoutes)
      console.log("生成的菜单")
      console.log(accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  generateRoutesMenu({ commit }, menuList) {
    return new Promise(resolve => {
      let accessedRoutes
      accessedRoutes = filterAsyncRoutesPerm( menuList)
      //console.log(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
